/************************************************************
 * Project Name         [Thinking_In_Java]
 * File Name            [Example_05_Thread_Clock_V2.java]
 * Creation Date        [04-Jul-2014]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ************************************************************/
package pkg_08_thread;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JFrame;
import javax.swing.JLabel;

/**
 * 线程时钟 - 使用java.util.Timer
 * 
 * @author 不落的太阳(Sean Yang)
 * @version 1.0
 * @since JDK 6
 * 
 */
public class Example_05_Thread_Clock_V2 {

	static class MyTimerTask extends TimerTask {

		private JLabel clock;

		MyTimerTask(JLabel clock) {
			super();
			this.clock = clock;
		}

		@Override
		public void run() {
			clock.setText(getTime());
		}

		private String getTime() {
			Calendar calendar = Calendar.getInstance();
			String time = calendar.get(Calendar.YEAR) + "年"
					+ (calendar.get(Calendar.MONTH) + 1) + "月"
					+ calendar.get(Calendar.DATE) + "日 ";

			int h = calendar.get(Calendar.HOUR_OF_DAY);
			int m = calendar.get(Calendar.MINUTE);
			int s = calendar.get(Calendar.SECOND);

			String ph = h < 10 ? "0" : "";
			String pm = m < 10 ? "0" : "";
			String ps = s < 10 ? "0" : "";
			return time + ph + h + "时" + pm + m + "分" + ps + s + "秒";
		}

	}

	public static void initClock() {
		JFrame frame = new JFrame("我的时钟");
		JLabel clock = new JLabel("clock");
		clock.setHorizontalAlignment(JLabel.CENTER);
		frame.add(clock, "Center");
		frame.setSize(240, 80);
		frame.setLocation(300, 300);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);

		Timer timer = new Timer();
		TimerTask task = new MyTimerTask(clock);
		timer.schedule(task, 1000);
	}

	public static void main(String[] args) {
		Example_04_Thread_Clock_V1.initClock();
	}

}
